<template>
  <div ref="chartContainer" class="chart-wrapper"></div>
</template>

<script setup>
import { ref, watch, onMounted, onBeforeUnmount } from "vue";
import ApexCharts from "apexcharts";
import { useAppStore } from "@/stores/app";

const appStore = useAppStore();
const props = defineProps({
  chartData: {
    type: Object,
    default: () => ({ datasets: [{ data: [] }], labels: [] }),
  },
});

const chartContainer = ref(null);
let chartInstance = null;
const FIXED_COLORS = ["#0ab39c", "#57cea7", "#dff7ea"];

// 获取主题颜色
const getThemeColors = () => {
  return appStore.darkMode
    ? { text: "#FFF", tooltipBg: "#2D2D3D" }
    : { text: "#666", tooltipBg: "#FFF" };
};

// 计算百分比和总数
const calculatePercentages = (data) => {
  const total = data.reduce((sum, val) => sum + Number(val), 0);
  return data.map((val) => ((Number(val) / total) * 100).toFixed(2) + "%");
};
const calculateTotal = (data) =>
  data.reduce((sum, val) => sum + Number(val), 0);

// 核心配置修改
const createChartOptions = () => {
  const colors = getThemeColors();
  const dataset = props.chartData.datasets[0];
  const percentages = calculatePercentages(dataset.data);
  const total = calculateTotal(dataset.data);

  return {
    chart: {
      type: "donut",
      height: "400px",
      toolbar: { show: false },
      background: "transparent",
    },
    series: dataset.data.map(Number),
    labels: props.chartData.labels,
    colors: FIXED_COLORS,
    plotOptions: {
      pie: {
        customScale: 0.8,
        donut: {
          size: "70%",
          labels: {
            show: true,
            total: {
              show: true,
              label: "产品总数",
              color: colors.text,
              fontSize: "16px",
              fontWeight: "bold",
              formatter: () => total.toString(), // 动态显示总数 [1](@ref)
            },
          },
        },
      },
    },
    dataLabels: {
      enabled: true,
      formatter: (val, { seriesIndex }) =>
        `${props.chartData.labels[seriesIndex]}: ${percentages[seriesIndex]}`,
      // 关键修改：启用延长线并外置标签 [5,8](@ref)
      connectors: {
        enabled: true, // 启用物理连接线
        stroke: {
          color: colors.text, // 延长线颜色与文字一致
          width: 1, // 线宽
        },
      },
      offsetX: 30, // 水平外移标签
      offsetY: 10, // 垂直外移标签
      style: {
        fontSize: "12px",
        colors: [colors.text],
        fontWeight: "normal",
      },
      background: { enabled: false },
    },
    stroke: { show: false }, // 隐藏环边框
    legend: {
      position: "bottom",
      labels: { colors: colors.text },
    },
    tooltip: {
      theme: appStore.darkMode ? "dark" : "light",
      style: { background: colors.tooltipBg },
      y: {
        formatter: (val, { seriesIndex }) =>
          `${props.chartData.labels[seriesIndex]}: ${val} (${percentages[seriesIndex]})`,
      },
    },
    responsive: [
      {
        breakpoint: 480,
        options: {
          chart: { width: 300 },
          dataLabels: {
            offsetX: 10, // 移动端调整标签位置
            offsetY: 5,
            connectors: { strokeWidth: 0.5 }, // 移动端减小线宽
          },
        },
      },
    ],
  };
};

// 初始化图表
const initChart = () => {
  if (!chartContainer.value) return;
  if (chartInstance) chartInstance.destroy();

  const chartOptions = createChartOptions();
  chartInstance = new ApexCharts(chartContainer.value, chartOptions);
  chartInstance.render();
};

// 数据更新监听
watch(
  () => props.chartData,
  (newData) => {
    if (chartInstance && newData.datasets?.[0]?.data) {
      const dataset = newData.datasets[0];
      const percentages = calculatePercentages(dataset.data);
      const total = calculateTotal(dataset.data);

      chartInstance.updateOptions(
        {
          series: dataset.data.map(Number),
          labels: newData.labels,
          plotOptions: {
            pie: {
              donut: {
                labels: {
                  total: { formatter: () => total.toString() },
                },
              },
            },
          },
          dataLabels: {
            formatter: (val, { seriesIndex }) =>
              `${newData.labels[seriesIndex]}: ${percentages[seriesIndex]}`,
          },
        },
        false,
        true
      ); // 第二个参数false表示不重绘动画，第三个参数true表示强制更新
    }
  },
  { deep: true }
);

// 主题切换监听
watch(
  () => appStore.darkMode,
  () => {
    if (chartInstance) {
      const newOptions = createChartOptions();
      chartInstance.updateOptions(newOptions);
    }
  }
);

onMounted(initChart);
onBeforeUnmount(() => {
  if (chartInstance) chartInstance.destroy();
});
</script>

<style scoped>
.chart-wrapper {
  height: 400px; /* 固定高度确保渲染区域 */
  width: 100%;
  position: relative;
}
</style>